﻿using Autofac;
using System.Linq;
using System.Reflection;
using Loong.Domain.Entities;

namespace Loong.Dapper.DbAccessors
{
    public static class DapperDbAccessorRegisterExtensions
    {
        public static void RegisterDbAccessor(this ContainerBuilder builder, Assembly assembly)
        {
            var entityGenericType = typeof(IEntity<>);
            var dbAccessorInterface = typeof(IDapperDbAccessor<>);
            var dbAccessorinterfaceWithPrimaryKey = typeof(IDapperDbAccessor<,>);
            var dbAccessorImplementation = typeof(DapperDbAccessorBase<>);
            var dbAccessorImplementationWithPrimaryKey = typeof(DapperDbAccessorBase<,>);
            var types = assembly.GetTypes().Where(type => !type.IsInterface && type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == entityGenericType));
            foreach (var type in types)
            {
                var primaryKeyType = type.GetInterfaces().Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == entityGenericType).First().GetGenericArguments()[0];
                if (primaryKeyType == typeof(int))
                {
                    var implementationType = dbAccessorImplementation.MakeGenericType(type);
                    var serviceType = dbAccessorInterface.MakeGenericType(type);
                    builder.RegisterType(implementationType).As(serviceType).InstancePerLifetimeScope();
                }
                else
                {
                    var implementationType = dbAccessorImplementationWithPrimaryKey.MakeGenericType(type, primaryKeyType);
                    var serviceType = dbAccessorinterfaceWithPrimaryKey.MakeGenericType(type, primaryKeyType);
                    builder.RegisterType(implementationType).As(serviceType).InstancePerLifetimeScope();
                }
            }
        }
    }
}
